package com.green.common.util.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Zip工具类.
 */
public class ZipUtil {

	protected static final Logger LOGGER = LoggerFactory.getLogger(ZipUtil.class);

	private static void create(List<String> filePaths, String zipName) {
		byte[] buffer = new byte[1024];
		ZipOutputStream out = null;
		String classPath = getClassPath();
		try {
			File f = new File(classPath + zipName);
			if (!f.exists()) {
				f.createNewFile();
			}
			out = new ZipOutputStream(new FileOutputStream(f));
			for (String path : filePaths) {
				File file = new File(classPath + path);
				FileInputStream fis = new FileInputStream(file);
				out.putNextEntry(new ZipEntry(file.getName()));

				int len;
				while ((len = fis.read(buffer)) > 0) {
					out.write(buffer, 0, len);

				}
				out.closeEntry();
				fis.close();

			}

		} catch (Exception e) {
			LOGGER.error("", e);
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					LOGGER.error("", e);
				}
			}
		}
	}

	/**
	 * 创建zip压缩文件，需要把jpdl和png一起打入zip包.
	 * 
	 * @param fileName
	 *            相对于classpath路径的相对路径
	 * @param zipName
	 *            相对于classpath路径的相对路径，默认为jpdl文件名.zip
	 */
	public static String createZip(String fileName, String zipName) {
		// eg: fileName=jpdl/test.jpdl.xml
		// 除了jpdl文件之外,还需要pgn文件打入到zip包一起发布

		String[] aryFileNames = fileName.split("\\.");
		List<String> fileNames = new ArrayList<String>();
		fileNames.add(fileName);
		fileNames.add(aryFileNames[0] + ".png");
		if (zipName == null || "".equals(zipName)) {
			zipName = aryFileNames[0] + ".zip";
		}
		create(fileNames, zipName);

		return zipName;
	}

	/**
	 * 获取服务器的classpath路径.
	 * 
	 * @return
	 */
	public static String getClassPath() {
		return Thread.currentThread().getContextClassLoader().getResource("").getPath();
	}

	public static void main(String[] args) throws Exception {
		List<String> paths = new ArrayList<String>();
		paths.add("jpdl/leave2.jpdl.xml");
		paths.add("jpdl/leave2.png");
		// ZipUtil.createZip(paths, "jpdl/leave2.zip");
		String classPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
		System.out.println("classPath:" + classPath);
		// ZipInputStream zis = new ZipInputStream(new FileInputStream(classPath + "jpdl/leave.zip"));

		String str = "jpdl/requestProject.jpdl.xml";
		String[] ary = str.split("\\.");
		System.out.println(ary[0]);

	}
}